function isObjectType (type) {
  return function (value) {
    return Object.prototype.toString.call(value) === type
  }
}

export const isObject = isObjectType('[object Object]')
export const isArray = isObjectType('[object Array]')
export const isFunction = isObjectType('[object Function]')
export const isString = isObjectType('[object String]')
export function isNumber (value) {
  if (!isNaN(value)) {
    return isObjectType('[object Number]')(value)
  }

  return false
}

export function VOID () { }

// 距离转换成字符串,单位米
export function toDistanceString (distance) {
  distance = parseFloat(distance)

  if (!isNumber(distance)) return 'N/A'
  else if (distance <= 0) return '0m'

  const kilometer = distance / 1000

  if (kilometer >= 1) return `${kilometer.toFixed(2)}km`

  return `${distance.toFixed(0)}m`
}

// 时间转换成字符串，单位毫秒
export function toTimeString (time) {
  time = Number(time)

  if (!isNumber(time)) return 'N/A'

  let runTime = parseInt(time / 1000)
  let days = Math.floor(runTime / 86400)
  runTime = runTime % 86400
  let hours = Math.floor(runTime / 3600)
  runTime = runTime % 3600
  let minutes = Math.floor(runTime / 60)
  runTime = runTime % 60
  let seconds = runTime

  let string = time <= 0 ? '0秒' : ''
  if (days > 0) string += `${days} 天 `
  if (hours > 0) string += `${hours} 小时 `
  if (minutes > 0) string += `${minutes} 分 `
  if (seconds > 0) string += `${seconds} 秒 `

  return string
}

// sources中value=undefined的数据不会覆盖target
export function assign (target, ...sources) {
  return Object.assign(target, ...sources.map(x =>
    Object.entries(x)
      .filter(([key, value]) => value !== undefined)
      .reduce(function (obj, [key, value]) {
        obj[key] = value
        return obj
      }, {})
  ))
}

// 转换为json
export function toJSON (data, callback) {
  try {
    const value = JSON.parse(data)
    isFunction(callback) && callback(value)
    return value
  } catch (e) {
    return null
  }
}

export function debounce (func, delay) {
  let timer = null

  return function () {
    let context = this
    let args = arguments

    clearTimeout(timer)

    timer = setTimeout(function () {
      func.apply(context, args)
    }, delay)
  }
}

// 判断是否在bbox中
export function inBBox (lng, lat, BBox) {
  if (lng < BBox[0] || lng > BBox[2]) return false
  if (lat < BBox[1] || lat > BBox[3]) return false

  return true
}

// 获取URL search参数中的数据
export function getURLSearch (search) {
  const searchString = search.slice(1)

  return searchString
    .split('&')
    .reduce(function (prev, curr, i, arr) {
      const p = curr.split('=')
      const pkey = p[0]
      const pvalue = p[1]

      if (p.length > 0 && pkey) {
        prev[decodeURIComponent(pkey)] = (pvalue !== undefined) ? decodeURIComponent(pvalue).trim() : ''
      }

      return prev
    }, {})
}

// 解释并获取到URL传递的地图参数
export function getMapParams (paramString) {
  if (!paramString) return {}

  const arr = paramString.split('/')
  let point = arr[0].split(',')

  if (point.length === 2) {
    point = point.map(n => parseFloat(n))
  } else {
    point = null
  }

  return {
    coord: point,
    mapId: arr[2] || undefined,
    floorId: arr[1] || undefined
  }
}

// 判断是否为空
export function isEmpty (value) {
  return value === undefined || value === '' || value === null
}

export function clone (val) {
  return JSON.parse(JSON.stringify(val))
}

export function deepClone (object) {
  let resultObject = {}
  for (let obj in object) {
    if (typeof (object[obj]) === 'object' && !Array.isArray(object[obj])) {
      let x = {}
      x[obj] = deepClone(object[obj])
      Object.assign(resultObject, x)
    } else {
      let x = {}
      x[obj] = object[obj]
      Object.assign(resultObject, x)
    }
  }
  return resultObject
}

export function downloadImage (name, imgsrc) {
  let image = new Image()
  // 解决跨域 Canvas 污染问题
  image.setAttribute('crossOrigin', 'anonymous')
  image.onload = function () {
    let canvas = document.createElement('canvas')
    canvas.width = image.width
    canvas.height = image.height
    let context = canvas.getContext('2d')
    context.drawImage(image, 0, 0, image.width, image.height)
    let url = canvas.toDataURL('image/png') // 得到图片的base64编码数据
    let a = document.createElement('a') // 生成一个a元素
    let event = new MouseEvent('click') // 创建一个单击事件
    a.download = name || 'photo' // 设置图片名称
    a.href = url // 将生成的URL设置为a.href属性
    a.dispatchEvent(event) // 触发a的单击事件
  }
  image.src = imgsrc
}

export function isContained(aa, bb) {
  if(!(aa instanceof Array) || !(bb instanceof Array) || ((aa.length < bb.length))) {
    return false;
  }
  //var aaStr = aa.toString();
  /*for(var i = 0; i < bb.length; i++) {
      if(aaStr.indexOf(bb[i]) < 0) return false;
  }*/
  for (var i = 0; i < bb.length; i++) {
    var flag = false;
    for(var j = 0; j < aa.length; j++){
      if(a[j] == bb[i]){
        flag = true;
        break;
      }
    }
    if(flag == false){
      return flag;
    }
  }
  return true;
}

export function hashCode(str){
  var hash = 0;
  if (str.length === 0) return hash;
  for (var i = 0; i < str.length; i++) {
    var char = str.charCodeAt(i);
    hash = ((hash<<5)-hash)+char;
    hash = hash & hash; // Convert to 32bit integer
  }
  return hash;
}
